<?php
/**
 * 周舟 hzboye010@163.com
 * addby sublime snippets
 */
namespace app\shop\api;
use app\common\api\BaseApi;
use app\shop\model\ProductPackageItem;
use app\shop\api\ProductPackageApi;

class ProductPackageItemApi extends BaseApi{

	const ADD      = "shop/ProductPackageItemApi/add";
	const SAVE     = "shop/ProductPackageItemApi/save";
	const GET_INFO = "shop/ProductPackageItemApi/getInfo";
	const SET_INC  = "shop/ProductPackageItemApi/setInc";
	const QUERY_NO_PAGING  = "shop/ProductPackageItemApi/queryNoPaging";

	/*private*/
	const QUERY_BY_PID = "shop/ProductPackageItemApi/queryByPid";
	const CHECK = "shop/ProductPackageItemApi/check";

  protected function _init(){
		$this->model = new ProductPackageItem();
	}

	public function check($pids,$sku_ids,$pack_id=0){
		if(!is_array($pids)) return $this->apiReturnErr('pids错误');;
		if(!is_array($sku_ids)) return $this->apiReturnErr('sku_ids错误');;
		if(count($pids) != count($sku_ids)) return $this->apiReturnErr('pids与sku_ids不匹配');

		$r = apiCall(ProductPackageApi::GET_INFO,[['id'=>$pack_id]]);
		if(!$r['status']) return $this->apiReturnErr($r['info']);
		if(empty($r['info']))  return $this->apiReturnErr('套餐已失效');
		if($r['info']['create_time']>time() || $r['info']['end_time']<time())
			  return $this->apiReturnErr('套餐已过期');
		$r = $this->queryNoPaging(['package_id'=>$pack_id],false,'p_id,sku_id');
		if(!$r['status']) return $this->apiReturnErr($r['info']);
		if(count($pids) != count($r['info'])) return $this->apiReturnErr('套餐商品不匹配');
		foreach ($r['info'] as $v) {
			$pid   = $v['p_id'];
			$skuid = intval($v['sku_id']);
			$k = array_search($pid, $pids);
			if(false !== $k){
				//bug
				// if(0 === $skuid || intval($sku_ids[$k]) === $skuid){
				// 	continue;
				// }else{
				// 	return $this->apiReturnErr('套餐商品:'.$pid.'规格错误');
				// }
			}else{
				return $this->apiReturnErr('套餐不完整,未包含:'.$pid);
			}
		}
		return $this->apiReturnSuc('pass');
	}
	//根据pid查询该商品所有套餐
	public function queryByPid($pid=0){
		$now = time();
		$model = new \think\model();
		$r = $model->query('select GROUP_CONCAT(package_id) as ids from itboye_product_package_item where p_id='.$pid);
		if(false === $r) return $this->apiReturnErr($model->getDbError());
		$ids = $r[0]['ids'];
		if(empty($ids)) return $this->apiReturnSuc([]);
		$model = new $this->model;
		$r = $model->alias('i')->where('i.package_id in ('.$ids.')')// and i.p_id <>'.$pid
		->join('left join itboye_product_package p on p.id=i.package_id and p.create_time<='.$now.' and p.end_time>'.$now)
		->join('left join itboye_product pro on pro.id=i.p_id')
		->join('left join itboye_product_image img on img.pid=i.p_id and img.type=6015')
		// ->join('left join itboye_product_sku s on s.product_id = i.p_id and (i.sku_id = 0 or s.id = i.sku_id)')
		->field('p.*,i.p_id,i.sku_id,i.is_main,pro.name,img.img_id')//,s.price,s.ori_price
		->select();
		if(false === $r) return $this->apiReturnErr($model->getDbError());
		return $this->apiReturnSuc($r);
	}
}